package com.htfyun.roobofactory.factorytest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.htfyun.roobofactory.BaseActivity;
import com.htfyun.roobofactory.R;
import com.htfyun.roobofactory.htfyunUtils.NvDataTool;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * Created by sst on 2018/7/7.
 */

public class FactoryTestMainActivity extends BaseActivity implements AdapterView.OnItemClickListener{

    private TextView txtReturn;
    private TextView txtAutoTest;

    private GridView gridView;
    private MyAdapter myAdapter;
    private Context mContext;

    private boolean autoTest = false;

    private Intent factoryPreviousServiceIntent;
    private boolean isFactoryPreviousServiceStarted = false;
    private boolean isFactoryPreviousClicked = false;
    List<FactoryTestItemsEnum> itemsEnumList = new ArrayList<>();
    private int autoTestCurrentItemsIndex = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_factorytest_main);

        mContext = this;

        txtReturn = (TextView) findViewById(R.id.txtReturn);
        txtAutoTest = (TextView) findViewById(R.id.txtAutoTest);
        txtAutoTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.anim_view_click);
                v.startAnimation(animation);

                autoTest = true;
                startFactoryPreviousService();

                autoTestCurrentItemsIndex = 0;
                startActivityForAutoTest();
            }
        });

        txtReturn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.anim_view_click);
                v.startAnimation(animation);

                ActivityCompat.finishAfterTransition(getActivity());

            }
        });

        gridView = (GridView) findViewById(R.id.gridView);


        for (FactoryTestItemsEnum itemsEnum : FactoryTestItemsEnum.values()) {
            itemsEnumList.add(itemsEnum);
        }

        Collections.sort(itemsEnumList, new Comparator<FactoryTestItemsEnum>() {
            @Override
            public int compare(FactoryTestItemsEnum o1, FactoryTestItemsEnum o2) {
                return o1.getOrderId() - o2.getOrderId();
            }
        });
        myAdapter = new MyAdapter(mContext, -1, itemsEnumList);

        gridView.setAdapter(myAdapter);

        gridView.setOnItemClickListener(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if(!Settings.canDrawOverlays(getApplicationContext())) {
                //启动Activity让用户授权
                Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION);
                intent.setData(Uri.parse("package:" + getPackageName()));
                startActivityForResult(intent,10000);
            }
        }
    }

    private void startActivityForAutoTest() {

        isFactoryPreviousClicked = false;
        FactoryTestItemsEnum itemsEnum = itemsEnumList.get(autoTestCurrentItemsIndex);
        Intent intent = new Intent(mContext, itemsEnum.getItemClass());
        startActivityForResult(intent, itemsEnum.getOrderId());
    }

    private void startActivityForAutoTestDelay() {

        getHandler().postDelayed(new Runnable() {
            @Override
            public void run() {
                startActivityForAutoTest();
            }
        }, 500);


    }

    @Override
    protected void onResume() {
        super.onResume();

        stopFactoryPreviousService();

    }

    @Override
    protected void onPause() {
        super.onPause();

        if (autoTest) {
            startFactoryPreviousService();
        }
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        stopService(new Intent(mContext, FactoryPreviousItemFloatWindowService.class));
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        FactoryTestItemsEnum itemsEnum = myAdapter.getItem(position);

        if (itemsEnum != null) {
            Intent intent = new Intent(mContext, itemsEnum.getItemClass());
            startActivityForResult(intent, itemsEnum.getOrderId());
        }

        autoTest = false;

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        FactoryTestItemsEnum itemsEnum = getItemsEnumWithOrderId(requestCode);

        if (itemsEnum != null) {

            if (resultCode == RESULT_OK) {

                itemsEnum.setResult(mContext, mContext.getString(R.string.test_result_pass));

                boolean allOk = true;
                for (FactoryTestItemsEnum item : FactoryTestItemsEnum.values()) {
                    if (!item.isPassed(getActivity())) {
                        allOk = false;
                        break;
                    }
                }

            } else if (resultCode == RESULT_CANCELED){

                itemsEnum.setResult(mContext, mContext.getString(R.string.test_result_fail));

            } else {

                itemsEnum.setResult(mContext, mContext.getString(R.string.test_result_unknown));

            }

            myAdapter.notifyDataSetChanged();
        }

        if (autoTest) {

            if (!isFactoryPreviousClicked) {
                autoTestCurrentItemsIndex++;
            }

            if (autoTestCurrentItemsIndex >= itemsEnumList.size()) {

                autoTest = false;

            } else {

                startActivityForAutoTestDelay();
            }
        }

    }

    private void startFactoryPreviousService() {

        if (isFactoryPreviousServiceStarted) {
            return;
        }

        isFactoryPreviousServiceStarted = true;

        if (factoryPreviousServiceIntent == null) {
            factoryPreviousServiceIntent = new Intent(mContext, FactoryPreviousItemFloatWindowService.class);
        }
        startService(factoryPreviousServiceIntent);

        IntentFilter filter = new IntentFilter(FactoryPreviousItemFloatWindowService.ACTION_FACTORY_PREVIOUS_CLICKED);
        filter.addAction(FactoryPreviousItemFloatWindowService.ACTION_FACTORY_RETURN_CLICKED);
        registerReceiver(previousClickReceiver, filter);
    }

    private void stopFactoryPreviousService() {

        if (!isFactoryPreviousServiceStarted) {
            return;
        }

        unregisterReceiver(previousClickReceiver);

        if (factoryPreviousServiceIntent == null) {
            factoryPreviousServiceIntent = new Intent(mContext, FactoryPreviousItemFloatWindowService.class);
        }
        stopService(factoryPreviousServiceIntent);

        isFactoryPreviousServiceStarted = false;

    }



    private FactoryTestItemsEnum getItemsEnumWithOrderId(int id) {
        for (FactoryTestItemsEnum itemsEnum : FactoryTestItemsEnum.values()) {
            if (itemsEnum.getOrderId() == id) {
                return itemsEnum;
            }
        }
        return null;
    }

    private BroadcastReceiver previousClickReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action == null) {
                return;
            }

            Log.e(TAG, "action = " + action);
            if (action.equals(FactoryPreviousItemFloatWindowService.ACTION_FACTORY_PREVIOUS_CLICKED)) {

                if (autoTestCurrentItemsIndex > 0) {
                    autoTestCurrentItemsIndex--;
                    isFactoryPreviousClicked = true;
                } else {
                    autoTest = false;
                }
            } else if (action.equals(FactoryPreviousItemFloatWindowService.ACTION_FACTORY_RETURN_CLICKED)) {
                autoTest = false;
            }
        }
    };

    private final class MyAdapter extends ArrayAdapter<FactoryTestItemsEnum> {


        public MyAdapter(@NonNull Context context, int resource, @NonNull List<FactoryTestItemsEnum> objects) {
            super(context, resource, objects);
        }

        @NonNull
        @Override
        public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView != null) {
                holder = (ViewHolder) convertView.getTag();
            }
            if (holder == null) {
                holder = new ViewHolder();
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                convertView = inflater.inflate(R.layout.item_factory_main, null);
                holder.txtName = (TextView) convertView.findViewById(R.id.txtName);
                holder.txtResult = (TextView) convertView.findViewById(R.id.txtResult);
                holder.itemView = convertView.findViewById(R.id.itemView);
            }

            FactoryTestItemsEnum itemsEnum = getItem(position);

            if (itemsEnum != null) {
                holder.txtName.setText(itemsEnum.getNameResId());
                holder.txtResult.setText(itemsEnum.getResult(getContext()));

                holder.itemView.setBackgroundColor(itemsEnum.getColor(getContext()));
            }

            return convertView;
        }
    }

    private final class ViewHolder {
        TextView txtName;
        TextView txtResult;
        View itemView;
    }

}
